package top.canyue.word_range.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import top.canyue.word_range.annotation.NotNullPassword;
import top.canyue.word_range.exception.NullPasswordException;
import top.canyue.word_range.pojo.dto.UserDto;
import top.canyue.word_range.pojo.po.User;

import java.util.Objects;

@Aspect
@Component
public class NotNullPasswordAspect {

    @Around("@annotation(notNullPassword)")
    public Object notNullPassword(ProceedingJoinPoint joinPoint, NotNullPassword notNullPassword) throws Throwable {
        Object[] args = joinPoint.getArgs();
        for(Object arg : args) {
            if(arg instanceof User) {
                if(!StringUtils.hasText(((User) arg).getPasswordHash()) || Objects.equals(((User) arg).getPasswordHash(), "")){
                    throw new NullPasswordException();
                }
            }
            if(arg instanceof UserDto) {
                if(!StringUtils.hasText(((UserDto) arg).getPassword()) || Objects.equals(((UserDto) arg).getPassword(), "")){
                    throw new NullPasswordException();
                }
            }
        }
        return joinPoint.proceed();
    }


}
